package com.leetcode;

/**
 * ReverseNumber..
 *
 * @author Lizhong
 * @date 2019/9/5
 */
public class ReverseNumber {
    public static void main(String[] args) {
        // int reverse = reverse(-2147483648);
        int reverse = reverse(-2147483412);
        // int reverse = reverse(-2483648);
        System.out.println(reverse);
        System.out.printf("%X",16);
    }

    static int reverse(int x) {
        int a[] = new int[10];
        int i = 0;

        int t = 0;
        if (x < 0)
            t = Math.negateExact(x);
        else if (x > 0) t = x;
        while (true) {
            int m = t % 10;
            int n = t / 10;
            a[i++] = m;
            if (n == 0) break;
            t = n;
        }
        int y = 0;

        for (int j = 0; j < i; j++) {
            y += a[j] * Math.pow(10, i - j - 1);
            if (y >= Integer.MAX_VALUE || y <= Integer.MIN_VALUE && (j + 1) != i) {
                return 0;
            }
        }
        if (x < 0) return -y;
        return y;
    }
    // 这种可以
    int reverse02(int x) {
        int max = 0x7fffffff, min = 0x80000000;//int的最大值最小值
        long temp = 0;
        while (x != 0) {
            temp = temp * 10 + x % 10;
            x /= 10;
        }

        if (temp > max || temp < min) {
            return 0;
        } else {
            return (int) temp;
        }
    }
}
